/**
 * $Id: SgipAdapter.java,v 1.2 2006/09/07 02:07:35 martin Exp $
 *
 * Copyright 2005 Skyinfo, Inc. All Rights Reserved.
 */
package com.haoxi.gateway.connector.impl;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.haoxi.gateway.common.GatewayInfo;
import com.haoxi.gateway.connector.Connector;
import com.haoxi.gateway.runner.QueueMgr;
import com.haoxi.gateway.runner.RunnerMgr;
import com.haoxi.gateway.runner.SGIPReciverThread;
import com.haoxi.gateway.sgip12msg.SGIPBindMessage;
import com.haoxi.gateway.sgip12msg.SGIPBindRepMessage;
import com.haoxi.gateway.sgip12msg.SGIPCommon;
import com.haoxi.gateway.sgip12msg.SGIPMessage;
import com.haoxi.gateway.sgip12msg.SGIPUnbindMessage;
import com.haoxi.gateway.sgip12msg.SequenceSower;

public class SgipAdapter implements SSEventListener {
    protected static final Log log = LogFactory.getLog(SgipAdapter.class);
    private SGIPDeliverServer server;
    private int maxConnCount = 0;
    private Connector connector;
    private int listenPort = 0;
    private static int count = 0;

    public SgipAdapter(int aListenPort, int maxConnCount, Connector conn) {
        this.listenPort = aListenPort;
        this.maxConnCount = maxConnCount;
        this.connector = conn;
    }

    // 在这里创造一个DeliverConnector
    public void onConnect(Socket socket) {
        String connName = connector.getConnName() + (++count);
        GatewayInfo gatewayInfo = RunnerMgr.getInstance().getGatewayInfo();
        Connector deliver = new SGIPDeliverConnector(gatewayInfo
                .getGatewayCode(), connName, gatewayInfo.getIcp_id(), connector
                .getLoginName(), connector.getPassword(), null, connector
                .getGatewayPort(), connector.getVersion(), gatewayInfo
                .getProtocolName());
        deliver.setSocInfo(socket);
        count++;
        new SGIPReciverThread("SGIPReciverThread" + count, deliver, QueueMgr
                .getInstance().getReciveQueue()).start();
    }

    // 拒绝SMC的过多连接，短连接结束会话
    public void onReject(Socket socket) {
        OutputStream out = null;
        DataInputStream in = null;
        int msgLength = 0;
        int commid = 0;
        byte[] reqbytes = new byte[0];
        SGIPMessage reqMessage = null;
        SGIPMessage respMessage = null;
        try {
            out = socket.getOutputStream();
            in = new DataInputStream(socket.getInputStream());
            msgLength = in.readInt();
            commid = in.readInt();
            if (SGIPCommon.MSG_BIND_BODY_LENGTH == msgLength
                    && SGIPCommon.SGIP_BIND == commid) {
                reqbytes = new byte[msgLength - 8];
                in.readFully(reqbytes);
                reqMessage = new SGIPBindMessage(reqbytes);
                log.debug(reqMessage.toString());
                // 连接过多，不允许对方连接
                respMessage = new SGIPBindRepMessage(3);
                respMessage.setSequenceId(reqMessage.getSequenceId());
                respMessage.setSrcNodeId(reqMessage.getSrcNodeId());
                respMessage.setTimeStamp(reqMessage.getTimeStamp());
                out.write(respMessage.getBytes());
                out.flush();
                // 发unbind消息，告诉对方关闭连接
                respMessage = new SGIPUnbindMessage();
                SequenceSower.setUnicomSequence(respMessage);
                out.write(respMessage.getBytes());
                out.flush();
                // 不需要读取剩余的消息了，没有任何意义
            }

        } catch (IOException ex) {
            log.debug("catch an IOException", ex);
        } finally {
            try {
                if (null != in) {
                    in.close();
                }
                if (null != out) {
                    out.close();
                }
                if (null != socket) {
                    socket.close();
                }
            } catch (Exception ex) {
                log.debug("catch an Exception ", ex);
            } finally {
                in = null;
                out = null;
                socket = null;
            }
        }

    }

    public synchronized void startService() {
        if (server != null)
            return;
        try {
            // 启动服务器监听
            server = new SGIPDeliverServer(listenPort, maxConnCount, this);
            server.beginListen();
        } catch (Exception exception) {
        }
    }
}
